<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="35%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="用户名" prop="userName">
        <ElInput v-model="formData.userName" placeholder="请输入用户名" />
      </ElFormItem>
      <ElFormItem label="用户编码" prop="userSn">
        <ElInput v-model="formData.userSn" placeholder="请输入用户编码" />
      </ElFormItem>
      <ElFormItem label="昵称" prop="nickName">
        <ElInput v-model="formData.nickName" placeholder="请输入昵称" />
      </ElFormItem>
      <ElFormItem label="所属机构" prop="deptId">
        <ElTreeSelect
          v-model="formData.deptId"
          :data="deptTreeData"
          :props="{ children: 'children', label: 'name', value: 'id' }"
          placeholder="请选择所属机构"
          check-strictly
          filterable
          clearable
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem label="手机号" prop="userPhone">
        <ElInput v-model="formData.userPhone" placeholder="请输入手机号" />
      </ElFormItem>
      <ElFormItem label="邮箱" prop="userEmail">
        <ElInput v-model="formData.userEmail" placeholder="请输入邮箱" />
      </ElFormItem>
      <ElFormItem label="性别" prop="userGender">
        <ElSelect v-model="formData.userGender">
          <ElOption label="男" value="男" />
          <ElOption label="女" value="女" />
          <ElOption label="未知" value="未知" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="状态" prop="status">
        <ElSelect v-model="formData.status">
          <ElOption label="在线" value="1" />
          <ElOption label="离线" value="2" />
          <ElOption label="异常" value="3" />
          <ElOption label="注销" value="4" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色" prop="userRoles">
        <ElSelect v-model="formData.userRoles" multiple>
          <ElOption
            v-for="role in roleList"
            :key="role.roleCode"
            :value="role.roleCode"
            :label="role.roleName"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="loading">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { createUser, getDeptTree, updateUser } from '@/api/system-manage'
  import { ROLE_LIST_DATA } from '@/mock/temp/formData'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { computed, nextTick, reactive, ref, watch } from 'vue'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<Api.SystemManage.UserListItem>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 加载状态
  const loading = ref(false)

  // 角色列表数据
  const roleList = ref(ROLE_LIST_DATA)

  // 机构树数据
  const deptTreeData = ref<any[]>([])

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: undefined,
    userName: '',
    userSn: '',
    nickName: '',
    deptId: '',
    userPhone: '',
    userEmail: '',
    userGender: '男',
    status: '1',
    userRoles: [] as string[]
  })

  // 表单验证规则
  const rules: FormRules = {
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    userSn: [
      { required: true, message: '请输入用户编码', trigger: 'blur' },
      { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
    ],
    nickName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    deptId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
    userPhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    userEmail: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    userGender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    userRoles: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }

  /**
   * 加载机构树数据
   */
  const loadDeptTreeData = async () => {
    try {
      const response = await getDeptTree()
      deptTreeData.value = response || []
    } catch (error) {
      console.error('加载机构树失败:', error)
      deptTreeData.value = []
    }
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData

    Object.assign(formData, {
      id: isEdit && row ? row.id : undefined,
      userName: isEdit && row ? row.userName || '' : '',
      userSn: isEdit && row ? row.userSn || '' : '',
      nickName: isEdit && row ? row.nickName || '' : '',
      deptId: isEdit && row ? row.deptId || '' : '',
      userPhone: isEdit && row ? row.userPhone || '' : '',
      userEmail: isEdit && row ? row.userEmail || '' : '',
      userGender: isEdit && row ? row.userGender || '男' : '男',
      status: isEdit && row ? row.status || '1' : '1',
      userRoles: isEdit && row ? (Array.isArray(row.userRoles) ? row.userRoles : []) : []
    })
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        loadDeptTreeData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后触发提交事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          loading.value = true

          // 转换数据格式以匹配后端UserRequestDTO
          const requestData = {
            // 字段名映射
            username: formData.userName,
            userSn: formData.userSn,
            nickname: formData.nickName,
            deptId: formData.deptId,
            phone: formData.userPhone,
            email: formData.userEmail,
            // 性别转换：男=1, 女=0, 未知=-1
            sex: formData.userGender === '男' ? 1 : formData.userGender === '女' ? 0 : -1,
            // 状态转换：1=启用(true), 其他=禁用(false)
            enabled: formData.status === '1',
            // 角色ID转换
            roleIds: formData.userRoles
          }

          if (dialogType.value === 'add') {
            // 新增用户
            await createUser(requestData)
          } else {
            // 更新用户
            await updateUser({
              ...requestData,
              userId: formData.id
            })
          }

          dialogVisible.value = false
          emit('submit')
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
        } finally {
          loading.value = false
        }
      }
    })
  }
</script>
